package com.example.photo_sharing.page.others;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.page.adapter.ImgShowAdapter;
import com.example.photo_sharing.tool.Impl.FocusLikeCollectImpl;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.example.photo_sharing.entity.FindList;
import com.example.photo_sharing.entity.FindListItem;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class Detailed extends AppCompatActivity {

    FindListItem data;

    private App app;
    private FocusLikeCollectImpl flc;
    private UserInfoSPImpl usp;
    private SharedPreferences sharedPreferences;

    private TextView title;
    private TextView date;
    private ImageButton avatar;
    private TextView username;
    private Button focus;
    private TextView introduce;
    private TextView like_num;
    private TextView collect_num;
    private ImageButton bt_like;
    private ImageButton bt_collect;

    private String userId = "0";
    private String likeId = "0";
    private String collectId = "0";

    private boolean SignOfLike;
    private boolean SignOfCollect;
    private boolean SignOfFocus;

    private FindList fl = new FindList();

    private RecyclerView recyclerView; //定义ReclerView控件
    private ArrayList<String> images = new ArrayList<>();
    private ImgShowAdapter myadpater;

    private boolean SignOfMine = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detial);

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide(); //隐藏标题栏
        }

        //接受传过来的参数
        Intent intent = getIntent();
        SignOfMine = intent.getBooleanExtra("Mine",false);
        System.out.println("从我的过来的标志是"+SignOfMine);
        app = (App)getApplication();
        data = (FindListItem) intent.getSerializableExtra("data");

        images = (ArrayList<String>) data.getImageUrlList();

        sharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);
        flc = new FocusLikeCollectImpl();

        SignOfLike = data.getHasLike();
        SignOfCollect = data.getHasCollect();
        SignOfFocus = data.getHasFocus();

        userId = usp.getUserId();

        initKJ();
//        get();
        initRecyclerView();
    }

//
//    private void get(){
//        new Thread(() -> {
//
//            // url路径
//            String url = "http://47.107.52.7:88/member/photo/share/detail?"
//                    +"shareId="+shareId
//                    +"&userId="+userId;
//
//            // 请求头
//            Headers headers = new Headers.Builder()
//                    .add("appId", app.getAppId())
//                    .add("appSecret", app.getAppSecret())
//                    .add("Accept", "application/json, text/plain, */*")
//                    .build();
//
//            //请求组合创建
//            Request request = new Request.Builder()
//                    .url(url)
//                    // 将请求头加至请求中
//                    .headers(headers)
//                    .get()
//                    .build();
//            try {
//                OkHttpClient client = new OkHttpClient();
//                //发起请求，传入callback进行回调
//                client.newCall(request).enqueue(callback);
//            }catch (NetworkOnMainThreadException ex){
//                ex.printStackTrace();
//            }
//        }).start();
//    }
//
//    /**
//     * 回调
//     */
//    private final Callback callback = new Callback() {
//        @Override
//        public void onFailure(@NonNull Call call, IOException e) {
//            //TODO 请求失败处理
//            e.printStackTrace();
//        }
//        @Override
//        public void onResponse(@NonNull Call call, Response response) throws IOException {
//            //TODO 请求成功处理
//            String responseData = response.body().string();
//            System.out.println(responseData);
//            jsonObject = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);
//
//        }
//    };

    private void initKJ(){
        title = findViewById(R.id.detail_title);
        date = findViewById(R.id.detail_time);
        avatar = findViewById(R.id.detail_bt_image);
        username = findViewById(R.id.detail_pusername);
        focus = findViewById(R.id.detail_bt_focus);
        introduce = findViewById(R.id.detail_content);
        like_num = findViewById(R.id.text_like_num);
        collect_num = findViewById(R.id.text_collect_num);
        bt_like = findViewById(R.id.detail_bt_like);
        bt_collect = findViewById(R.id.detail_bt_collect);


        //时间戳转换为时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(data.getCreateTime())));

        System.out.println(data.getId());

        date.setText(sd);
        title.setText(data.getTitle());
        username.setText("  "+data.getUsername());
        introduce.setText(data.getContent());
        like_num.setText((data.getLikeNum()==null?0:data.getLikeNum()) + "");
        collect_num.setText((data.getCollectNum()==null?0:data.getCollectNum())+"");

        //设置点赞的图标
        if(SignOfLike){
            Picasso.get().load(app.getImg_like_true()).into(bt_like);
        }
        else {
            Picasso.get().load(app.getImg_like_false()).into(bt_like);
        }

        //设置收藏的图标
        if(SignOfCollect){
            Picasso.get().load(app.getImg_collect_true()).into(bt_collect);
        }
        else {
            Picasso.get().load(app.getImg_collect_false()).into(bt_collect);
        }
        //设置关注的样式
        if(SignOfFocus){
            flc.setImgFocus(focus);
        }
        else{
            flc.setImgDefocus(focus);
        }
        //添加收藏的事件
        bt_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SignOfCollect){
                    flc.deCollect(collectId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"取消收藏成功",Toast.LENGTH_LONG).show();
                    SignOfCollect = flc.setImgDecollect(bt_collect,collect_num);
                    data.setHasCollect(false);
                    data.setLikeNum(data.getLikeNum()-1);
                }
                else {
                    flc.setCollect(data.getId(),userId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"收藏成功",Toast.LENGTH_LONG).show();
                    SignOfCollect = flc.setImgCollect(bt_collect,collect_num);
                    data.setHasCollect(true);
                    data.setCollectNum((data.getCollectNum()!=null?data.getCollectNum():0)+1);
                }
            }
        });

        //添加点赞的事件
        bt_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SignOfLike){
                    flc.deLike(likeId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"取消点赞成功",Toast.LENGTH_LONG).show();
                    SignOfLike = flc.setImgDelike(bt_like,like_num);
                    data.setHasLike(false);
                    data.setLikeNum(data.getLikeNum()-1);
                }
                else {
                    flc.setLike(data.getId(),userId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"点赞成功",Toast.LENGTH_LONG).show();
                    SignOfLike = flc.setImgLike(bt_like,like_num);
                    data.setHasLike(true);
                    data.setLikeNum((data.getLikeNum()!=null?data.getLikeNum():0) +1);
                }
            }
        });

        //添加关注的事件
        focus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(data.getPUserId()+" ---- "+userId);

                if(SignOfFocus){
                    flc.deFocus(data.getPUserId(),userId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"取消关注成功",Toast.LENGTH_LONG).show();
                    SignOfFocus = flc.setImgDefocus(focus);
                    data.setHasLike(false);
                }
                else {
                    flc.setFocus(data.getPUserId(),userId);
                    app.setDelay(500);
                    Toast.makeText(Detailed.this,"关注成功",Toast.LENGTH_LONG).show();
                    SignOfFocus = flc.setImgFocus(focus);
                    data.setHasLike(true);
                }
            }
        });
        //点进个人主页
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), OtherPeople.class);
                intent.putExtra("Pid",data.getPUserId());
                intent.putStringArrayListExtra("urls",(ArrayList<String>) data.getImageUrlList());
                intent.putExtra("data",data);
                startActivity(intent);
            }
        });

        if(SignOfMine){
            Picasso.get().load(usp.getInfo().getAvatar()).into(avatar);
            focus.setVisibility(View.INVISIBLE);
            username.setText("  "+usp.getInfo().getUsername());
            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        }

    }

    private void initRecyclerView() {
        recyclerView = (RecyclerView)findViewById(R.id.Detail_pic_list);
        System.out.println("asdasdasdadsasdasd--------------"+images.size());

        myadpater = new ImgShowAdapter(this,images);
        recyclerView.setAdapter(myadpater);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));

        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

        myadpater.setOnItemClickListener(new ImgShowAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, String img) {
                System.out.println(img);
            }
        });
    }
}
